package logic

import (
	"context"
	"day15/api/internal/svc"
	"day15/api/internal/types"
	"day15/api/pkg"
	"day15/app_config"
	"day15/rpc/user"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserLoginLogic) UserLogin(req *types.UserLoginRequest) (resp *types.ApiResponse, err error) {
	//// todo: add your logic here and delete this line
	res, err := l.svcCtx.UserSrv.UserLogin(l.ctx, &user.UserLoginReq{
		Username: req.Username,
		Password: req.Password,
	})
	if err != nil {
		return &types.ApiResponse{
			Code: 0,
			Msg:  "账号或者密码错误",
			Data: nil,
		}, nil
	}
	userId := res.Id
	token, err := pkg.GetJwtToken(app_config.AppConf.JwtConfig.AccessKey, time.Now().Unix(), int64(app_config.AppConf.JwtConfig.ExpireTime), string(userId))
	if err != nil {
		return &types.ApiResponse{
			Code: 0,
			Msg:  "jwt生成失败",
			Data: nil,
		}, nil
	}
	return &types.ApiResponse{
		Code: 200,
		Msg:  "登录成功",
		Data: token,
	}, nil
}
